package com.wobito.common.interceptor;

import com.wobito.common.constants.BusinessException;
import com.wobito.common.constants.ErrorCode;
import com.wobito.common.utils.MD5Utils;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author Wangbaba
 * @Date 2024/9/9 15:26
 * @Version 1.0
 */
@Component
public class SignatureInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 提取请求中的时间戳
        String timestampFromRequest = request.getHeader("Timestamp");
        // 提取请求中的签名
        String signatureFromRequest = request.getHeader("Signature");
        if (StringUtils.isEmpty(timestampFromRequest)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"非法请求:Timestamp");
        }
        if (StringUtils.isEmpty(signatureFromRequest)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"非法请求:Signature");
        }
        // 验证签名逻辑
        boolean isValid = verifySignature(timestampFromRequest, signatureFromRequest);
        if (!isValid) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"无效的签名");
        }
        return true;
    }

    private boolean verifySignature(String timestampFromRequest, String signatureFromRequest) {
        String sign= MD5Utils.getMD5Hash(MD5Utils.salt+"-"+timestampFromRequest);
        if (!signatureFromRequest.equals(sign)){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"无效的签名");
        }
        return true;
    }
}
